<template>
  <div class="knowledge-container">
    <h1>糖尿病知识库</h1>

    <!-- 搜索区域 -->
    <div class="search-area">
      <el-input
        v-model="searchQuery"
        placeholder="搜索糖尿病相关知识..."
        clearable
        @keyup.enter="searchKnowledge"
        @clear="clearSearch"
      >
        <template #append>
          <el-button @click="searchKnowledge" :icon="Search">搜索</el-button>
        </template>
      </el-input>
    </div>

    <!-- 知识列表 -->
    <div class="knowledge-list">
      <el-card
        v-for="item in filteredKnowledge"
        :key="item.id"
        class="knowledge-item"
        shadow="hover"
      >
        <template #header>
          <div class="knowledge-header">
            <h3>{{ item.title }}</h3>
            <el-tag :type="item.type === '饮食' ? 'success' : item.type === '运动' ? 'warning' : 'info'">
              {{ item.type }}
            </el-tag>
          </div>
        </template>
        <div class="knowledge-content">
          {{ item.content }}
        </div>
        <div class="knowledge-footer">
          <span class="knowledge-date">{{ formatDate(item.date) }}</span>
          <el-button type="primary" size="small" @click="viewDetail(item.id)">查看详情</el-button>
        </div>
      </el-card>
    </div>

    <!-- 分页 -->
    <div class="pagination">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :total="totalItems"
        layout="prev, pager, next"
        @current-change="handlePageChange"
      />
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue';
import { Search } from '@element-plus/icons-vue';
import axios from 'axios';

// 数据库连接配置
const apiBaseUrl = 'http://your-api-server.com/api';
const dbConfig = {
  headers: {
    'Content-Type': 'application/json',
    'Authorization': 'Bearer your-access-token'
  }
};

// 搜索相关
const searchQuery = ref('');
const currentPage = ref(1);
const pageSize = ref(10);
const totalItems = ref(0);
const knowledgeList = ref([]);

// 模拟知识数据
const mockKnowledge = [
  {
    id: 1,
    title: '糖尿病饮食指南',
    type: '饮食',
    content: '糖尿病患者应控制碳水化合物摄入，增加膳食纤维...',
    date: '2023-05-15'
  },
  {
    id: 2,
    title: '适合糖尿病患者的运动',
    type: '运动',
    content: '建议每周至少150分钟中等强度有氧运动...',
    date: '2023-06-20'
  },
  {
    id: 3,
    title: '血糖监测频率',
    type: '监测',
    content: '根据病情不同，监测频率从每天1次到7次不等...',
    date: '2023-04-10'
  }
];

// 获取知识库数据
const fetchKnowledge = async () => {
  try {
    // 实际项目中替换为真实API调用
    // const response = await axios.get(`${apiBaseUrl}/knowledge`, dbConfig);
    // knowledgeList.value = response.data;

    // 使用模拟数据
    knowledgeList.value = mockKnowledge;
    totalItems.value = mockKnowledge.length;
  } catch (error) {
    console.error('获取知识库数据失败:', error);
    knowledgeList.value = mockKnowledge; // 失败时使用模拟数据
    totalItems.value = mockKnowledge.length;
  }
};

// 搜索知识
const searchKnowledge = async () => {
  if (searchQuery.value.trim()) {
    try {
      // 实际项目中替换为真实API调用
      // const response = await axios.get(`${apiBaseUrl}/knowledge?q=${searchQuery.value}`, dbConfig);
      // knowledgeList.value = response.data;

      // 使用模拟搜索
      knowledgeList.value = mockKnowledge.filter(item =>
        item.title.includes(searchQuery.value) ||
        item.content.includes(searchQuery.value)
      );
      totalItems.value = knowledgeList.value.length;
      currentPage.value = 1;
    } catch (error) {
      console.error('搜索失败:', error);
    }
  } else {
    fetchKnowledge();
  }
};

// 清空搜索
const clearSearch = () => {
  fetchKnowledge();
};

// 查看详情
const viewDetail = (id) => {
  // 实际项目中可跳转到详情页或显示模态框
  console.log('查看知识详情:', id);
  // 示例: 获取详情数据
  // const detail = knowledgeList.value.find(item => item.id === id);
  // 显示详情逻辑...
};

// 格式化日期
const formatDate = (dateString) => {
  return new Date(dateString).toLocaleDateString();
};

// 分页处理
const handlePageChange = (page) => {
  currentPage.value = page;
};

// 过滤后的知识列表
const filteredKnowledge = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value;
  const end = start + pageSize.value;
  return knowledgeList.value.slice(start, end);
});

// 初始化加载数据
onMounted(() => {
  fetchKnowledge();
});
</script>

<style scoped>
.knowledge-container {
  padding: 20px;
  max-width: 1000px;
  margin: 0 auto;
}

h1 {
  color: #303133;
  margin-bottom: 30px;
  text-align: center;
}

.search-area {
  margin-bottom: 30px;
  max-width: 600px;
  margin-left: auto;
  margin-right: auto;
}

.knowledge-list {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(400px, 1fr));
  gap: 20px;
  margin-bottom: 30px;
}

.knowledge-item {
  transition: all 0.3s ease;
}

.knowledge-item:hover {
  transform: translateY(-5px);
}

.knowledge-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.knowledge-content {
  margin: 15px 0;
  line-height: 1.6;
  color: #606266;
}

.knowledge-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 15px;
}

.knowledge-date {
  font-size: 12px;
  color: #909399;
}

.pagination {
  display: flex;
  justify-content: center;
  margin-top: 30px;
}
</style>
